package com.wfl.sampling.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.exceptions.ClientException;
import com.wfl.sampling.aop.RunTimeGet;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Slf4j
@Data
@Component
public class AIiOSSUtils {
    @Value("${aliyun.oss.endpoint}")
    private  String setEndpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private  String setAccessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private  String setAccessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String setBucketName;

    @Getter
    private static String endpoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    @Getter
    private static String bucketName;
    @Getter
    private static OSS ossClient;
    @PostConstruct
    public void init() {
        endpoint = this.setEndpoint;
        accessKeyId = this.setAccessKeyId;
        accessKeySecret = this.setAccessKeySecret;
        bucketName = this.setBucketName;
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

//    private final EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

//    static {
//        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
//    }

    @RunTimeGet
    public String upload(MultipartFile multipartFile) throws IOException {
        InputStream is = multipartFile.getInputStream();
        String originalFilename = multipartFile.getOriginalFilename();
        assert originalFilename != null;
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileExtension;
        ossClient.putObject(bucketName, fileName, is);
//        is.close();
//        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        return url;
    }

    public void shutdown() {
        ossClient.shutdown();
    }
//    public String upload(MultipartFile multipartFile) throws IOException{
//        InputStream is = multipartFile.getInputStream();
//        String originalFilename = multipartFile.getOriginalFilename();
//        assert originalFilename != null;
//        String fileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
//        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
//        ossClient.putObject(bucketName,fileName,is);
//        String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
//        ossClient.shutdown();
//        return url;
//
//    }
//    public List<String> uploads(List<MultipartFile> multipartFiles) throws IOException {
//        List<String> urls = new ArrayList<>();
//        ExecutorService executorService = Executors.newFixedThreadPool(Math.min(15, multipartFiles.size())); // 使用不超过9个线程
//        try {
//            for (MultipartFile multipartFile : multipartFiles) {
//                executorService.execute(() -> {
//                    try (InputStream is = multipartFile.getInputStream()) {
//                        String originalFilename = multipartFile.getOriginalFilename();
//                        assert originalFilename != null;
//                        String fileName;
//                        fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//                        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//                        ossClient.putObject(bucketName, fileName, is);
//                        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
//                        urls.add(url);
//                        ossClient.shutdown();
//                    } catch (IOException e) {
//                        log.info("上传失败");
//                    }
//                });
//            }
//        } finally {
//            executorService.shutdown();
//        }
//        return urls;
//    }
//public List<String> uploads(List<MultipartFile> multipartFiles) {
//    List<String> urls = Collections.synchronizedList(new ArrayList<>()); // 使用线程安全的List
//    ExecutorService executorService = Executors.newFixedThreadPool(9); // 使用固定大小为9的线程池
//    try {
//        for (MultipartFile multipartFile : multipartFiles) {
//            executorService.execute(() -> {
//                try (InputStream is = multipartFile.getInputStream()) {
//                    String originalFilename = multipartFile.getOriginalFilename();
//                    assert originalFilename != null;
//                    String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//                    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//                    ossClient.putObject(bucketName, fileName, is);
//                    String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
//                    urls.add(url);
//                    ossClient.shutdown();
//                } catch (IOException e) {
//                    log.error("文件上传失败", e); // 记录异常信息
//                }
//            });
//        }
//    } finally {
//        executorService.shutdown();
//    }
//    return urls;
//}
public List<String> uploads(List<MultipartFile> multipartFiles) {
    ExecutorService executorService = Executors.newFixedThreadPool(9);
    List<Future<String>> futures = new ArrayList<>();
    try {
        for (MultipartFile multipartFile : multipartFiles) {
            Future<String> future = executorService.submit(() -> {
                try (InputStream is = multipartFile.getInputStream()) {
                    String originalFilename = multipartFile.getOriginalFilename();
                    assert originalFilename != null;
                    String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                    ossClient.putObject(bucketName, fileName, is);
                    String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
                    ossClient.shutdown();
                    return url;
                } catch (IOException e) {
                    log.error("文件上传失败", e);
                    return null;
                }
            });
            futures.add(future);
        }


        // 将Future列表转换为String列表
        List<String> urls = new ArrayList<>();
        for (Future<String> future : futures) {
            try {
                String url = future.get(); // 获取Future对象的结果
                if (url != null) {
                    urls.add(url);
                }
            } catch (InterruptedException | ExecutionException e) {
                log.error("获取上传结果失败", e);
            }
        }

        return urls;
    } finally {
        executorService.shutdown();
    }
}



    public AIiOSSUtils() throws ClientException {
    }

}
